<?php

namespace Modules\Shop\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Shop\Entities\Category;
use Modules\Shop\Http\Requests\CategoryRequest;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {

         //获取所有数据
        //$categorys=Category::get();
        //获取树状分类数据
        $categorys = Category::getTreeCategory();
        return view('shop::category.index',compact('categorys'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {

        return view('shop::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        Category::create($request->all());
       //设置闪存信息并返回
        session()->flash('success','分类添加成功');
        return back();
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show()
    {
        return view('shop::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit($id)
    {
        //获取当前id的所有数据
        $category=Category::find($id);
        //获取所有树状分类数据
        $categorys = Category::getTreeCategory($category);
        return view('shop::category.edit',compact('category','categorys'));
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(CategoryRequest $request,$id)
    {
        //找到对应id的分类数据
        $category=Category::find($id);
        //dd($category->toArray());
        //获取post数据
        $post=$request->all();
        $category->cname=$post['cname'];
        $category->pid=$post['pid'];
        $category->save();
        //设置闪存并跳转
        session()->flash('success','修改成功');
        return redirect()->route('category.index');
    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
        //获取当前id对应的所有数据
        $category=Category::find($id);
        if(Category::hasChildCategory($category)){
            //设置闪存提示信息，并返回
            session()->flash('danger','请先删除所有子类，然后在进行操作');
            return back();
        }
        //删除数据
        Category::destroy($id);
        //设置闪存提示信息，并返回
        session()->flash('success','删除分类成功');
        return back();
    }
}
